package com.zhentao.login.config;

import cn.hutool.core.bean.BeanUtil;
import com.zhentao.login.exception.ServiceException;
import com.zhentao.login.utils.HttpStatus;
import com.zhentao.nlz.project.login.TUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class SecurityUtil {

    public static Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /*
    *  获取用户对象
    * */
    public static TUser getUser(){
        TUser user =(TUser) getAuthentication().getPrincipal();
        return user;
    }
    /*
     *  获取用户id
     * */
    public static Integer getUserId(){
        TUser user =(TUser) getAuthentication().getPrincipal();
        Integer userId = user.getUserId();
        if(BeanUtil.isEmpty(userId)){
            throw new ServiceException(HttpStatus.ERROR,"");
        }
        return userId;
    }
    /*
     *  获取用户账户
     * */
    public static String getUsername(){
        TUser user =(TUser) getAuthentication().getPrincipal();
        String username = user.getUsername();
        if(BeanUtil.isEmpty(username)){
            throw new ServiceException(HttpStatus.ERROR,"");
        }
        return username;
    }
}
